package cetc54.zhtx.client;

import cetc54.zhtx.common.ConstantPool;
import cetc54.zhtx.start.ClientListenStatus;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.ScheduledFuture;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * ping服务器，每两秒ping一次
 * @author lipeng
 */
@Slf4j
public class ClientPingHandler extends ChannelInboundHandlerAdapter {



    private final HeartBeatClient heartBeatClient;

    private final  ClientListenStatus listenStatus;


    public ClientPingHandler(HeartBeatClient heartBeatClient, ClientListenStatus listenStatus) {
        this.heartBeatClient=heartBeatClient;
        this.listenStatus=listenStatus;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        pingServer(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        listenStatus.inActiveEvent();
    }

    /**
     * 每2秒发送心跳包
     * @param channel 通道
     */
    private void pingServer(Channel channel){

        ScheduledFuture<?> future = channel.eventLoop().schedule(() -> {
            if (channel.isActive()) {
                channel.writeAndFlush(ConstantPool.HEART_BEAT);
            } else {
                log.info("与备机服务器断开连接,准备开始重试");
                channel.closeFuture();
                throw new RuntimeException();
            }
        },ConstantPool.HEART_BEAT_TIME, TimeUnit.SECONDS);
        future.addListener(future1 -> {
            if(future1.isSuccess()){
                pingServer(channel);
            }else{
                //重连机制
                heartBeatClient.connect();
            }
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}
